function extractIPFromCandidate(candidate) {
    console.log(candidate);
    const ipRegex =
        /([0-9]{1,3}(\.[0-9]{1,3}){3}|([a-f0-9]{1,4}:){7}[a-f0-9]{1,4})/gi;
    const match = candidate.match(ipRegex);
    return match ? match[0] : null;
}
async function getPublicIP() {
    try {
        const response = await fetch('https://api.ipify.org?format=json');
        const data = await response.json();
        return data.ip;
    } catch (error) {
        return '无法获取公网 IP';
    }
}
export const getRealIP = () => {
    return new Promise((resolve) => {
        const pc = new RTCPeerConnection({
            iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
        });

        pc.createDataChannel('');
        pc.createOffer().then((offer) => pc.setLocalDescription(offer));

        pc.onicecandidate = (e) => {
            if (e.candidate) {
                const cand = e.candidate.candidate;
                const type = cand.split(' ')[7];

                // 优先提取 srflx/relay 类型的公网 IP
                if (type === 'srflx' || type === 'relay') {
                    const ip = extractIPFromCandidate(cand);
                    if (ip) resolve(ip);
                }
            } else {
                // 没有更多候选时尝试备选方案
                getPublicIP().then(resolve);
            }
        };
    });
};

// 需要做跨域处理
export const getIpAndAddressSohu = () => {
    const config = {
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json;charset=UTF-8',
        },
    }
    axios.get('/apiSohu/cityjson?ie=utf-8', config).then(res => {
        console.log(res.data) 
        // const info = res.data.substring(19, res.data.length - 1)
        // console.log(info) 
        // this.ip = JSON.parse(info).cip
        // this.address = JSON.parse(info).cname
    })
}
